<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('order.quick Search Fields') })"
        >
            <template #default >
                <el-button 
                    type="primary" 
                    @click="handleBatchEdit"
                    :disabled="!baTable.table.selection?.length"
                    style="margin-left: 15px;"
                >
                    <Icon name="el-icon-Edit" />
                    <span class="table-header-operate-text">批量修改</span>
                </el-button>
                <el-dropdown @command="handleImport" style="margin-left: 15px;">
                    <el-button type="primary">
                        <Icon name="el-icon-Upload" />
                        <span class="table-header-operate-text">导入</span>
                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="order">订单导入</el-dropdown-item>
                            <el-dropdown-item command="image">图片导入</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef"></Table>

        <!-- 表单 -->
        <PopupForm />

        <!-- 导入对话框 -->
        <el-dialog
            class="ba-operate-dialog"
            :close-on-click-modal="false"
            v-model="importDialog.show"
            :title="importDialog.title"
            width="50%"
        >
            <template #header>
                <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                    {{ importDialog.title }}
                </div>
            </template>
            <el-scrollbar v-loading="importDialog.loading" class="ba-table-form-scrollbar">
                <div
                    class="ba-operate-form"
                    :style="config.layout.shrink ? '':'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
                >
                    <div style="margin-bottom: 15px; text-align: right;">
                        <el-link 
                            type="primary" 
                            :href="importDialog.type === 'order' ? 'http://tmp8.iiiii5.cn/static/template/importOrderTemplate.xlsx' : 'http://tmp8.iiiii5.cn/static/template/importImageTemplate.zip'"
                        >
                            下载{{ importDialog.type === 'order' ? '订单' : '图片' }}导入模板
                        </el-link>
                    </div>
                    <el-form
                        ref="formRef"
                        @submit.prevent=""
                        @keyup.enter="handleSubmit(formRef)"
                        :model="importForm"
                        :label-position="config.layout.shrink ? 'top' : 'right'"
                        :label-width="baTable.form.labelWidth + 'px'"
                    >
                        <FormItem 
                            :label="importDialog.type === 'order' ? '订单文件' : '图片文件'" 
                            type="file" 
                            v-model="importForm.file" 
                            prop="file"
                            :input-attr="{
                                limit: 1,
                                drag: true,
                                autoUpload: false,
                                showFileList: true,
                                accept: importDialog.type === 'order' ? '.xlsx,.xls' : '.zip',
                                uploadText: '拖拽文件到此处或点击上传',
                                tipText: importDialog.type === 'order' ? '请上传Excel文件' : '请上传图片文件',
                                headers: {'X-Requested-With': 'XMLHttpRequest'}
                            }"
                        />
                    </el-form>
                </div>
            </el-scrollbar>
            <template #footer>
                <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                    <el-button @click="importDialog.show = false">{{ t('Cancel') }}</el-button>
                    <el-button 
                        v-blur 
                        :loading="importDialog.submitLoading" 
                        @click="handleSubmit(formRef)" 
                        type="primary"
                    >
                        {{ t('Upload') }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <BatchEditForm 
            v-model:dialogVisible="batchEditDialog.show"
            :baTable="baTable"
            @success="handleBatchEditSuccess"
        />
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { ArrowDown, UploadFilled } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import PopupForm from './popupForm.vue'
import BatchEditForm from './batchEditForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import { useConfig } from '/@/stores/config'
import FormItem from '/@/components/formItem/index.vue'

defineOptions({
    name: 'order',
})

const { t } = useI18n()
const config = useConfig()
const tableRef = ref()
const formRef = ref<FormInstance>()
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/Order/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
            { label: t('order.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
            { label: t('order.wul_name'), prop: 'wul_name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.wul_no'), prop: 'wul_no', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.wul_status'), prop: 'wul_status', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.wul_time'), prop: 'wul_time', align: 'center', operator: 'eq', sortable: 'custom', width: 160 },
            { label: t('order.shouh_name'), prop: 'shouh_name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.shouh_phone'), prop: 'shouh_phone', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.shouh_address'), prop: 'shouh_address', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.image'), prop: 'image', align: 'center', render: 'image', operator: false },
            { label: t('order.order_status'), prop: 'order_status', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '待付款': t('order.order_status 待付款'), '待发货': t('order.order_status 待发货'), '待收货': t('order.order_status 待收货') } },
            { label: t('order.end_tuik_time'), prop: 'end_tuik_time', align: 'center', operator: 'eq', sortable: 'custom', width: 160 },
            { label: t('order.order_no'), prop: 'order_no', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.goods_name'), prop: 'goods_name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.goods_sku'), prop: 'goods_sku', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.goods_price'), prop: 'goods_price', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('order.num'), prop: 'num', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('order.youh_price'), prop: 'youh_price', align: 'center', operator: 'RANGE', sortable: false },
            { label: '发货时间', prop: 'cn_fah_time', align: 'center', operator: 'eq', sortable: 'custom', width: 160 },
            { label: '下单时间', prop: 'xiad_time', align: 'center', operator: 'eq', sortable: 'custom', width: 160 },
            { label: '付款时间', prop: 'fuk_time', align: 'center', operator: 'eq', sortable: 'custom', width: 160 },
            { label: '成交时间', prop: 'chengj_time', align: 'center', operator: 'eq', sortable: 'custom', width: 160 },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: { order_status: '待付款' },
    }
)

provide('baTable', baTable)

const importDialog = reactive({
    show: false,
    title: '',
    type: '',
    loading: false,
    submitLoading: false,
})

const importForm = reactive({
    file: '',
})

const batchEditDialog = reactive({
    show: false
})

const handleImport = (command: string) => {
    importDialog.type = command
    importDialog.title = command === 'order' ? '订单导入' : '图片导入'
    importDialog.show = true
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    importDialog.submitLoading = true
    try {
        const formData = new FormData()
        formData.append('file', importForm.file)
        const response = await baTable.api.postData(
            'import' + (importDialog.type === 'order' ? 'Order' : 'Image'),
            formData
        )
        if (response.code === 1) {
            ElMessage.success('导入成功')
            importDialog.show = false
            await baTable.getIndex()
        } else {
            ElMessage.error(response.msg || '导入失败')
        }
    } catch (error) {
        ElMessage.error('上传失败，请重试')
    } finally {
        importDialog.submitLoading = false
    }
}

const handleBatchEdit = () => {
    if (!baTable.table.selection?.length) {
        ElMessage.warning('请选择要修改的数据')
        return
    }
    batchEditDialog.show = true
}

const handleBatchEditSuccess = () => {
    baTable.getIndex()
}

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss">
.upload-demo {
    text-align: center;
}
.el-upload__tip {
    margin-top: 10px;
    color: #666;
}
</style>
